package pkg.drowne.org;

import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

public class login extends Activity implements OnClickListener, Runnable {
	
	// Preference file
	public static final String PREF_FILE = "pf2";
	private SharedPreferences preferences;
	
	private String username, password, hashedPassword;
	
	private ProgressDialog pd;
	
	// Views
	private ImageButton loginButton, resetButton;
	private EditText editUsername, editPassword;
	private boolean connected;
	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
	        WindowManager.LayoutParams.FLAG_FULLSCREEN,
	        WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        // creates the activity
        setContentView(R.layout.login);
        
        // variables initialization
        connected = false;
        
        // Views
        registerViews();
        setupOnClickListeners();
       
        fillDataifExist();

    }
    
    private void fillDataifExist() {
	
    	// check for the saved preferences  
        // get the preferences file ready
    	//preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		
    	preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
		
		boolean first = preferences.getBoolean("first", true);
		String user = preferences.getString("username", "");
		String pass = preferences.getString("password", "");
	
		if(!first){
			editUsername.setText(user);
			editPassword.setText(pass);
			
		}
		
		
	}

	private void registerViews() {

    	loginButton = (ImageButton) this.findViewById(R.id.btnLogin);
    	resetButton = (ImageButton) this.findViewById(R.id.btnReset);
    	editUsername = (EditText) this.findViewById(R.id.edtUsername);
    	editPassword = (EditText) this.findViewById(R.id.edtPassword);
	
    }

	public void setupOnClickListeners() {
    	
        loginButton.setOnClickListener(this);
        resetButton.setOnClickListener(this);
    	
    }

	public void onClick(View v) {
		
		switch(v.getId()) {
			
		case R.id.btnLogin:
			// login button pressed
			// validate the data locally
			
			try {
				fillUserAndPass();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			
			if (!connected) {
				pd = ProgressDialog.show(this, "Logging in...", "Please wait...", true, false);
            	Thread cThread = new Thread(this);
            	cThread.start();
            }

			break;
			
		case R.id.btnReset:
			// reset button pressed
			// so reset each text field
			editUsername.setText("");
			editPassword.setText("");
			break;
				
		}
		
	}

	private void fillUserAndPass() throws NoSuchAlgorithmException {
		
		username = editUsername.getText().toString();
		password = editPassword.getText().toString();
		hashedPassword = Utils.md5Hash(password);
		
	}

	public void run() {
		
		boolean answer = Connection.checkLogin(username, hashedPassword);
		if(answer) {
		    
			// login successfully
			savePrefs();
			this.finish();

			handler.sendEmptyMessage(1);
			
			startActivity(new Intent(getBaseContext(), NewGameMenu.class));
			
		} else {
			// wrong login
			handler.sendEmptyMessage(0);
		}
		
		
	}

	private boolean savePrefs() {

		// get the preferences file ready
		preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
		//preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		
		username = editUsername.getText().toString();
		password = editPassword.getText().toString();
		
		// saves values in the preferences file
		preferences.edit().putString("username", username).commit();
		preferences.edit().putString("password", password).commit();
		preferences.edit().putBoolean("first", false).commit();
		
		return true;
	}
	

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();
			if (msg.what == 1) {
				Utils.showToastShort(getBaseContext(), "Logged In");
			} else {
				Utils.showToastShort(getBaseContext(), "Wrong username/password combination");
			}

		}
	};
	
}
